package Lock_2;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class MessageQueue {
    private String message;
    private boolean empty = true;
    private final Lock lock = new ReentrantLock();
    private final Condition notEmpty = lock.newCondition();
    private final Condition notFull = lock.newCondition();

    public void put(String message) {
        lock.lock();
        try {
            while (!empty) {
                notFull.await();
            }
            this.message = message;
            empty = false;
            System.out.println(Thread.currentThread().getName() + " 生产: " + message);
            notEmpty.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public String take() {
        lock.lock();
        try {
            while (empty) {
                notEmpty.await();
            }
            String result = message;
            empty = true;
            System.out.println(Thread.currentThread().getName() + " 消费: " + result);
            notFull.signal();
            return result;
        } catch (InterruptedException e) {
            e.printStackTrace();
            return null;
        } finally {
            lock.unlock();
        }
    }
}

public class Condition使用_生产者消费者模型 {
    public static void main(String[] args) {
        final MessageQueue queue = new MessageQueue();

        // 创建10个生产者线程
        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                public void run() {
                    for (int j = 0; j < 5; j++) {
                        queue.put("消息-" + Thread.currentThread().getName() + "-" + j);
                    }
                }
            }, "生产者-" + i).start();
        }

        // 创建10个消费者线程
        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                public void run() {
                    for (int j = 0; j < 5; j++) {
                        queue.take();
                    }
                }
            }, "消费者-" + i).start();
        }
    }
}